<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="广告二维码时间维护">
                    <form class="form-inline" id="labelWidth" @submit.prevent v-el:sform>
                        <form-input title="广告二维码所属商户名称" :up-table="true" :search="true" name="baMchtName" label-width="width:180px"></form-input>
                        <form-input title="广告二维码名称" :up-table="true" :search="true" name="baName" label-width="width:180px"></form-input>
                        <!--<form-select title="商户号" :up-table="true" :search="true" name="mchtId" :options="mchtList" :value.sync="mchtVal"></form-select>-->
                        <form-input title="电子券所属商户名称" :up-table="true" :search="true" name="mchtName"
                                    id="mcht" label-width="width:180px"></form-input>
                        <!--<form-select title="电子券名称" :up-table="true" :search="true" name="couponId" :options="baIdList" :value.sync="baId"></form-select>-->
                        <form-input title="电子券名称" :up-table="true" :search="true" name="couponName"
                                    id="coupon" label-width="width:180px"></form-input>
                        <span class="pull-right">
                            <button type="reset" @click="reset" class="btn btn-warning pull-right b_tn">重置</button>
                            <v-button theme="primary" @click="search" class="pull-right b_tn">查询</v-button>
                            <v-button theme="success" @click="add" class="pull-right create b_tn">新增二维码时间</v-button>

                        </span>


                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table></table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>

        <modal-container  @close="timeclose" :title="operate==='create'?'新增广告二维码时间':'修改广告二维码时间'" v-el:add-time-modal
                         v-ref:add-time-modal>
            <time-operate v-ref:time-operate v-if="timeShow" :operate="operate"  @close="timeclose" :edit-data="editTimeData"></time-operate>
        </modal-container>
        <modal-container title="新增" v-el:add-modal v-ref:modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:add-mform>
                <div class="add-body modal-body">
                    <table-modal :item="item" :columns-set="columnsAddSet" v-ref:item></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <modal-container title="详情" v-el:detail-modal v-ref:detail-modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:detail-mform>
                <div class="modal-body">
                    <!-- <table-modal :item="item" :columns-set="columnsDetailSet"></table-modal> -->
                    <table class="table table-bordered table-hover">
                        <tr>
                            <td style="width:50%">广告二维码所属商户名称</td>
                            <td>{{item.baMchtName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">广告二维码名称</td>
                            <td style="word-wrap:break-word;word-break:break-all;">{{item.baName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%;">电子券所属商户名称</td>
                            <td style="word-wrap:break-word;word-break:break-all;">{{item.mchtName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">电子券名称</td>
                            <td style="word-wrap:break-word;word-break:break-all;">{{item.couponName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">开始时间</td>
                            <td>{{item.beginTime}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">结束时间</td>
                            <td>{{item.endTime}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">电子券领取间隔</td>
                            <td>{{item.intervalDay}}天</td>
                        </tr>
                        <tr>
                            <td style="width:50%">状态</td>
                            <td>{{item.baStat == '1' ? '关闭' : '开启'}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">定位标识</td>
                            <td>{{potFlag == '0' ? '是':'否'}}</td>
                        </tr>
                        <tr v-show='checkDate'>
                            <td style="width:50%">签到日期</td>
                            <td>{{checkDate}}</td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                </div>
            </form>
        </modal-container>
        <!-- /.row-->
    </div>
    <!-- /.content -->
</template>

<script>
//解决datatables弹窗警告
$.fn.dataTable.ext.errMode = 'none';
import { createDataTable } from "ui/collections/general.js";
import {
    dateTime
} from "ui/collections/general.js";
import TimeOperate from "./time.operate";
var serialize = require("form-serialize");

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            _array: [],
            item: {},
            columnsSet: [],
            mchtList: [],
            typeList: [],
            mchtVal: "",
            operate: "create",
            editData: null,
            editTimeData: null,
            timeShow: false, //组件的生成由用户决定

            baIdList: [], //广告id列表
            baId: "",
            potFlag: "", //详情的定位标志
            checkDate: "" //详情签到日期
        }),
        components: {
            TimeOperate
        },
        watch: {
            async mchtVal (v) {
                if (v != '') {
                    await this.$post({
                        url: "/api/v2" + projectName_Url + "/plat/qr/bannertime/queryCoupon/" + v,
                        method: "POST"
                    }).then(
                        response => {
                            let list = response.content;
                            this.baIdList = list.map(ele => {
                                return {
                                    key: ele.couponName,
                                    value: ele.couponId
                                };
                            });
                            this.$set("baIdList", this.baIdList);
                            this.baIdList.unshift({key: "所有电子券", value: ""});
                        },
                        error => {
                        }
                    );
                } else {
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                    await this.$post({
                        url: "/api/v2" + projectName_Url + "/plat/qr/bannertime/queryCoupon/" + mchtId,
                        method: "POST"
                    }).then(
                        response => {
                            let list = response.content;
                            this.baIdList = list.map(ele => {
                                return {
                                    key: ele.couponName,
                                    value: ele.couponId
                                };
                            });
                            this.$set("baIdList", this.baIdList);
                            this.baIdList.unshift({key: "所有电子券", value: ""});
                        },
                        error => {
                        }
                    );
                }
            }
        },
        methods: {
            //新增广告
            add () {
                if (this.operate !== "create") {
                    this.operate = "create";
                }
                this.timeShow = true;
                $(this.$els.addTimeModal).modal("show");
            },
            //关闭广告时间操作dialog
            timeclose (go) {
                if (go) dataTable.draw(false); // 只有提交修改后才局部刷新页面
                this.$refs.timeOperate.$destroy(); //强制注销组件
                this.timeShow = false;
                $(this.$els.addTimeModal).modal("hide");
            },
            //还原弹出框位置
            resetBindDrag () {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function () {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function () {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            },
            getNameList (data) {
                let self = this;
                self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/qr/bannertime/queryCouponMcht",
                    method: "POST"
                }).then(
                    response => {
                        let list = response.content;
                        self.mchtList = list.map(ele => {
                            return {
                                key: ele.mchtName,
                                value: ele.mchtId
                            };
                        });
                        self.mchtList.unshift({key: "所有商户", value: ""})
                    },
                    error => {
                    }
                );
            }
        },
        created () {
            //主页面datatable所用数组
            columnsSet = [
                {
                    title: "广告二维码id",
                    data: "baId",
                    visible: false,
                    className: "operate"
                },
                {
                    title: "商户id",
                    data: "mchtId",
                    visible: false,
                    className: "operate"
                },
                {
                    title: "广告二维码id",
                    data: "baDefId",
                    visible: false,
                    className: "operate"
                },
                {
                    title: "电子券id ",
                    data: "couponId",
                    visible: false,
                    readonly: true,
                    className: "operate"
                },
                {
                    title: "广告二维码所属商户",
                    data: "baMchtName",
                    className: "operate"
                },
                {
                    title: "广告二维码名称",
                    data: "baName",
                    className: "operate"
                },
                {
                    title: "电子券所属商户名称",
                    data: "mchtName",
                    className: "operate"
                },
                {
                    title: "电子券名称",
                    data: "couponName",
                    className: "operate"
                },
                {
                    title: "开始时间",
                    data: "beginTime",
                    className: "operate",
                    render: data => {
                        return data.slice(0, 2) + ":" + data.slice(2);
                    }
                },
                {
                    title: "结束时间",
                    data: "endTime",
                    className: "operate",
                    render: data => {
                        return data.slice(0, 2) + ":" + data.slice(2);
                    }
                },
                {
                    title: "相关操作",
                    className: "operate",
                    width: "120px",
                    render: function (value, type, row) {
                        if (row.baStat == '1') {
                            return `
                                    <button type="button" class="btn btn-primary btn-sm editTime same">修改</button>
                                    <button type="button" class="btn btn-danger btn-sm delete same">删除</button>
                                    <button type="button" class="btn btn-defalt btn-sm detail same">详情</button>
                                      `;
                        } else {
                            return `
                  <button type="button" class="btn btn-defalt btn-sm detail same">详情</button>
                `

                        }

                    }
                }
            ];
        },
        ready: async function () {
            this.$set("columnsSet", columnsSet);
            var self = this;
            // self.getNameList();
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.sform, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    let baId = self.baId;

                    // _data.baId = self.baId;
                    var res = await self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/qr/bannertime/searchCoupon",
                        data: _data,
                        method: "POST"
                    });
                    if (res.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: res.content
                        });
                    }
                    callback({
                        recordsTotal: res.content.total || 0,
                        recordsFiltered: res.content.total || 0,
                        data: res.content.list || []
                    });
                    //过期的优惠券 有效日期显示红色
                    if (res.content.list != '' && res.content.list != null) {
                        for (var i in res.content.list) {
                            // console.log(parseInt(res.content.list[i].validatyEnd))
                            //获取当前时间戳
                            var d= new Date();
                            var d2 = d.getFullYear() + "-"+ (d.getMonth() + 1) +"-"+ d.getDate();
                            //月是一位数时自动补齐0
                            if((d.getMonth() + 1) < 10){
                                var d2 = d.getFullYear() + "-"+ "0"+(d.getMonth() + 1) +"-"+ d.getDate();
                            }
                            //日是一位数时自动补齐0
                            if(d.getDate() < 10){
                                var d2 = d.getFullYear() + "-"+ "0"+(d.getMonth() + 1) +"-"+"0"+d.getDate();
                            }
                            var str = d2.replace(/-/g,'');

                            if(parseInt(res.content.list[i].validatyEnd)-parseInt(str) < 0){
                                // console.log(parseInt(res.content.list[i].validatyEnd)-parseInt(str))
                                var trs = $('tbody tr td:nth-child(4)');
                                $(trs[i]).css('color','red');

                            }
                        }
                    }
                }
            });
            //点击新增时间
            $('.create').click(function () {
                $('.creBox').css('display', 'block');
            });

            //点击删除
            $(self.$el).on("click", ".delete", async function () {
                var Row = $(this).closest("tr").get(0);
                let baDefId = dataTable.row(Row).data().baDefId;
                let baName = dataTable.row(Row).data().baName;
                var result = await Midway.confirm({
                    title: "删除广告二维码时间",
                    content: "是否要删除:" + baName + "?"
                });
                var result = await self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/qr/bannertime/" + baDefId,
                    method: "DELETE"
                });
                Midway.alert({
                    title: "操作提示",
                    content: "删除成功"
                });
                // dataTable.ajax.reload();
                dataTable.draw(false);
            });
            $(self.$el).on("click", ".editTime", async function () {
                var Row = $(this).closest("tr").get(0);
                self.operate = "edit";
                self.editTimeData = Object.assign(
                    {},
                    JSON.parse(
                        JSON.stringify(dataTable.row(Row).data(), function (key, val) {
                            if (key == "beginTime" || key == "endTime") {
                                return val.slice(0, 2) + ":" + val.slice(2);
                            } else {
                                return val;
                            }
                        })
                    )
                );
                self.timeShow = true;
                $(self.$els.addTimeModal).modal("show");
            });
            $(self.$el).on("click", ".detail", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                //显示时间
                self.item.beginTime = dataArray.beginTime.slice(0, 2) + ":" + dataArray.beginTime.slice(2);
                self.item.endTime = dataArray.endTime.slice(0, 2) + ":" + dataArray.endTime.slice(2);
                //请求定位标识 签到日期
                self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/qr/banner/queryByBaIdOrBaMchtId",
                    data: {"baId": dataArray.baId, "baMchtId": dataArray.baMchtId},
                    method: "POST"
                }).then(
                    response => {
                        let list = response.content;
                        for (var i in list) {
                            self.potFlag = list[i].potFlag;
                            let date = list[i].checkDate;
                            self.checkDate = dateTransform(date);
                        }

                    },
                    error => {
                    }
                );
                $(self.$els.detailModal).modal('show');
            })
        },
        rules: {},
        beforeDestroy () {
            $(this.$el).off("click");
        }
    };
</script>


<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }
</style>

<style>
    .form-inline .name {
        margin-top: 2px !important;
    }

    .form-inline div #mcht {
        margin-left: 2.5% !important;
    }

    .form-inline div #coupon {
        margin-left: 4.2% !important;
    }
</style>
